import { createSlice } from '@reduxjs/toolkit'

// default user info
const initState = () => {
  return {
    username: '',
    auth: 0,
    meta: {},
    token: localStorage.getItem('persist:root')
      ? JSON.parse(JSON.parse(localStorage.getItem('persist:root'))?.user)
          ?.token
      : null
  }
}
const userSlice = createSlice({
  name: 'user',
  initialState: initState,
  reducers: {
    // init user state
    init(state) {
      const initS = initState()
      Object.keys(initS).forEach((key) => {
        state[key] = initS[key]
      })
      state.token = ''
    },
    // set user state method
    setUserInfo(state, action) {
      const inputState = action.payload
      Object.keys(inputState).forEach((key) => {
        state[key] = inputState[key]
      })
    }
  }
})

export const { init, setUserInfo } = userSlice.actions

export default userSlice.reducer
